<template>
    <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <h2 class="text-center  margin-bottom">{{title}}</h2>

            <a-form layout="inline" @keyup.enter.native="searchQuery">
                <a-row :gutter="24">

                    <a-col :md="8" :sm="24">
                        <a-form-item label="提交时间">
                            <a-range-picker
                                :show-time="{ format: 'HH:mm' }"
                                :placeholder="['开始时间', '结束时间']"
                                v-model="rangeTime"
                                format="YYYY-MM-DD HH:mm"
                                @change="handleDateChange"
                            />
                        </a-form-item>
                    </a-col>

                    <!--<a-col :md="8" :sm="24" v-if="customerList.length <= 0">-->
                        <!--<a-form-item label="机构选择">-->
                            <!--<a-select placeholder="选择机构" v-model="queryParam.customerNumber">-->
                                <!--<a-select-option v-for="(item,index)  in customerList" :key="index"-->
                                                 <!--:value="item['customerNumber']">-->
                                    <!--{{ item['customerName'] }}-->
                                <!--</a-select-option>-->
                            <!--</a-select>-->
                        <!--</a-form-item>-->
                    <!--</a-col>-->

                    <a-col :md="8" :sm="24" v-if="(customerList.length <= 0 ) && (!userInfo.customerNumber)">
                        <a-form-item label="产生单位">
                            <select-customer-list @change="changeCustomer"></select-customer-list>
                        </a-form-item>
                    </a-col>

                    <a-col :md="8" :sm="24" v-if="isShowTip && customerList.length <= 0">
                        <span style="color: red; font-size: 16px; letter-spacing:2px;">请输入产生单位！</span>
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <!-- 查询区域-END -->

        <div class="table-operator" style="display: flex;justify-content: space-between;align-items: center;">
            <div>
                <a-button type="primary" @click="searchQuery" icon="search">查询数据列表</a-button>
            </div>
            <div>
                <a-button type="primary" icon="printer" v-print="'#printTableList'">打印</a-button>
                <a-button type="primary" icon="download" @click="handleMwExportXlsForImages">
                    导出Excel
                </a-button>
            </div>
        </div>

        <!-- table区域-begin -->
        <div>
            <CheckboxWasteType @change="changeWasteType"></CheckboxWasteType>
        </div>

        <!-- table区域-begin -->
        <div>
            <a-table
                    ref="table"
                    size="middle"
                    bordered
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"
                    :pagination="false"
                    :loading="loading"
                    class="j-table-force-nowrap"
            >
                <template slot="htmlSlot" slot-scope="text">
                    <div v-html="text"></div>
                </template>
                <template slot="imgSlot" slot-scope="text">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                    <img v-else :src="text" height="25px" alt style="width: auto;height: 50px;"/>
                </template>
            </a-table>
        </div>

        <div v-show="false">
            <div id="printTableList">
                <h2 style="text-align: center;font-weight: bold;">{{title}}</h2>
                <h3 v-if="rangeTime.length">时间 ： {{rangeTime[0]}} 至 {{rangeTime[1]}}</h3>
                <a-table
                        size="small"
                        bordered
                        rowKey="id"
                        :columns="columns"
                        :dataSource="dataSource"
                        :pagination="false"
                >
                    <template slot="htmlSlot" slot-scope="text">
                        <div style="color: black !important;" v-html="text"></div>
                    </template>
                </a-table>
            </div>
        </div>
    </a-card>

</template>

<script>
    /**
     * create by Jane
     * 二维码回溯数据统计 wasteSubmitStatic
     */
    import '@/assets/less/TableExpand.less'
    import { mixinDevice } from '@/utils/mixin'
    import { JeecgListMixin } from '@/mixins/JeecgListMixin'
    import SelectCustomerList from '@/components/Jane/SelectCustomerList'
    import CheckboxWasteType from '@/components/Jane/CheckboxWasteType'

    import { downloadFile } from '../../../api/manage'
    import * as user from '../../../api/user'
    import * as customer from '../../../api/customer' // 模糊下拉查询

    export default {
        mixins: [JeecgListMixin, mixinDevice],
        components: {
            SelectCustomerList,
            CheckboxWasteType,
        },
        data() {
            return {
                title: '机构废物提交数据统计',
                userInfo : this.$store.getters.userInfo,
                /* 数据源 */
                dataSource: [],
                rangeTime: [],
                queryParam: {
                    customerNumber: null,
                    customerDepartmentId: null,
                    creatTimeBegin: null,
                    creatTimeEnd: null
                },
                // 表头
                columns: [],
                url: {
                    exportXlsUrlOkForImages: '/hc/hcRecycleBagcode/exportInspection'
                },
                customerList: [],
                loading: false,
                wasteTypeList: [], // 废物类型列表 (原始数据)
                wasteId: [],  // 选择的废物
                isShowTip: true // 是否显示输入产生单位的提示
            }
        },
        mounted() {
        },
        methods: {
            async initDictConfig() {
                let date = new Date();
                let time1 = new Date(date.setHours(0,0,0,0)).Format('yyyy-MM-dd hh:mm');
                let time2 = new Date(date.setHours(0,0,0,0) + (1000 * 60 * 60 * 24 - 1)).Format('yyyy-MM-dd hh:mm');
                this.rangeTime = [time1, time2];
                this.queryParam.creatTimeBegin = time1;
                this.queryParam.creatTimeEnd = time2;

                let userInfo = this.$store.getters.userInfo;
                if(userInfo.customerNumber){
                    this.queryParam.customerNumber = userInfo.customerNumber
                    this.isShowTip = false
                }

                let orgList = await user.getAllCustomerByUserId()
                if (orgList) {
                this.customerList = orgList || []
                    if (orgList[0]) {
                        this.queryParam.customerNumber = orgList[0].customerNumber
                    }
                }

                await this.setColumns()
                await this.getDataSource()
            },
            handleDateChange(value, dateString) {
                this.rangeTime = dateString
                if (dateString[0]) {
                    this.queryParam.creatTimeBegin = dateString[0]
                }
                if (dateString[1]) {
                    this.queryParam.creatTimeEnd = dateString[1]
                }
            },
            // 设置表格头部信息
            setColumns() {
                let data = this.wasteTypeList
                let cols = []
                data.forEach((item, index) => {
                    if (item.wasteTypeName) {
                        let child = [];
                        (item['children'] || []).forEach((val, i) => {
                            let info = this.wasteId.find(v => v === val.id)
                            if (info) {
                                // 塑料输液瓶（袋）、玻璃输液瓶（袋）单位换成kg
                                if(val.id == "1366228898901467138" || val.id == "1366274806234079234"){
                                    val.priceUnit = "kg"
                                }
                                child.push({
                                    title: val.wasteTypeName,
                                    dataIndex: 'id',
                                    key: `${index}-${i}`,
                                    children: [
                                        {
                                            title: '袋数',
                                            align: 'center',
                                            dataIndex: 'id',
                                            key: `${index}-${i}-1-1`,
                                            customRender: function(vv, waste, index) {
                                                let info = (waste['maps']).find((v) => v.waste_type === val.id)
                                                if (info) {
                                                    vv = info.bagNum
                                                }
                                                const obj = {
                                                    children: vv || '',
                                                    attrs: {}
                                                }
                                                if (waste.colSpan) {
                                                    obj.children =
                                                <div style="color:red;font-weight:600;">{vv || 0} </div>
                                                    obj.attrs.colSpan = 1
                                                }
                                                return obj
                                            }
                                        },
                                        {
                                            title: `重量${val.priceUnit ? `(${val.priceUnit})` : ''}`,
                                            align: 'center',
                                            dataIndex: 'id',
                                            key: `${index}-${i}-1-2`,
                                            customRender: function(vv, waste, index) {
                                                let info = (waste['maps']).find((v) => v.waste_type === val.id)
                                                if (info) {
                                                    vv = info.wasteOriginalValue
                                                }
                                                const obj = {
                                                    children: vv || '',
                                                    attrs: {}
                                                }
                                                if (waste.colSpan) {
                                                    obj.children =
                                                <div style="color:red;font-weight:600;">{vv || 0} kg</div>
                                                    obj.attrs.colSpan = 1
                                                }
                                                return obj
                                            }
                                        }
                                    ]
                                })
                            }
                        })
                        if (child.length) {
                            let obj = {
                                title: item.wasteTypeName,
                                dataIndex: 'id',
                                key: `${index}`,
                                children: child
                            }
                            cols.push(obj)
                        }
                    }
                })
                this.columns = [
                    {
                        title: '序号',
                        dataIndex: 'id',
                        key: 'rowIndex',
                        width: 60,
                        align: 'center',
                        scopedSlots: { customRender: 'htmlSlot' },
                        customRender: (text, row, index) => {
                            const obj = {
                                children: parseInt(index) + 1,
                                attrs: {}
                            }
                            if (row.colSpan) {
                                obj.children = <div style="color:red;font-weight:600;">合计</div>
                                obj.attrs.colSpan = row.colSpan
                            }
                            return obj
                        }
                    },
                    {
                        title: '机构名称',
                        align: 'center',
                        dataIndex: 'customerName',
                        key: 'customerName',
                        customRender: (value, row, index) => {
                            const obj = {
                                children: value,
                                attrs: {}
                            }
                            if (row.colSpan) {
                                obj.attrs.colSpan = 0
                            }
                            return obj
                        }
                    },
                    {
                        title: '部门/科室',
                        align: 'center',
                        dataIndex: 'customerDepartmentName',
                        key: 'customerDepartmentName',
                        customRender: (value, row, index) => {
                            const obj = {
                                children: value,
                                attrs: {}
                            }
                            if (row.colSpan) {
                                obj.attrs.colSpan = 0
                            }
                            return obj
                        }
                    },
                    ...cols
                ]
            },
            changeCustomer(value, option) {
                this.queryParam.customerNumber = value;
                this.isShowTip = false;
            },
            // 废物类型选择改变
            changeWasteType(info,wasteList) {
                this.wasteId = info.ids;
                this.queryParam.wasteId = info.ids.join(',');
                this.wasteTypeList = wasteList;
                this.setColumns();
                this.getDataSource();
            },
            searchQuery: function() {
                this.getDataSource()
            },
            getDataSource: async function() {
                if (this.queryParam.customerNumber) {
                    let res = await customer.getEveryDayStatisticV2(this.queryParam)
                    if (res) {
                        this.dataSource = res.records || []
                        let sumDate = res.sumList || []
                        this.dataSource.push({
                            colSpan: 3,
                            maps:sumDate
                        })
                    }
                }
            },
            handleMwExportXlsForImages() {
                let param = { ...this.queryParam }
                let name = `台账数据统计-${new Date().FormatDate()}.xls`
                downloadFile(this.url.exportXlsUrlOkForImages, name, param)
            }
        }
    }
</script>
<style scoped>
    @import '~@assets/less/common.less';
</style>
